package com.zxy.supplier_system.server.xinyuan.repository

import com.zxy.supplier_system.server.xinyuan.controller.XinyuanOrdersController
import com.zxy.supplier_system.server.xinyuan.entity.XinyuanOrder
import jakarta.persistence.criteria.Predicate
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.stereotype.Repository
import java.time.OffsetDateTime

@Repository
interface XinyuanOrderRepository : JpaRepository<XinyuanOrder, Int>,
    JpaSpecificationExecutor<XinyuanOrder> {

    // 使用 Specification 实现灵活查询
    fun findByCriteria(
        criteria: XinyuanOrdersController.OrderSearchCriteria,
        pageable: Pageable
    ): Page<XinyuanOrder> {
        return findAll(createSpecification(criteria), pageable)
    }

    // 创建动态查询条件
    private fun createSpecification(
        criteria: XinyuanOrdersController.OrderSearchCriteria
    ): Specification<XinyuanOrder> {
        return Specification { root, query, builder ->
            val predicates = mutableListOf<Predicate>()

            // 家电/数码类型
            criteria.isHomeAppliance?.let {
                predicates.add(builder.equal(root.get<Boolean>("isHomeAppliance"), it))
            }


            // 支付时间范围
            criteria.startDate?.let {
                predicates.add(builder.greaterThanOrEqualTo(root.get("createdDateTime"), it))
            }

            criteria.endDate?.let {
                predicates.add(builder.lessThanOrEqualTo(root.get("createdDateTime"), it))
            }

            // 消费者姓名
            criteria.name?.let {
                predicates.add(
                    builder.like(
                        builder.lower(root.get("name")),
                        "%${it.lowercase()}%"
                    )
                )
            }

            // 组合所有条件
            builder.and(*predicates.toTypedArray())
        }
    }

    // 其他查询方法...
    fun findByPaymentDateTimeBetween(
        start: OffsetDateTime,
        end: OffsetDateTime,
        pageable: Pageable
    ): Page<XinyuanOrder>

}